<template>
  <t-dialog
    :visible="visible"
    @update:visible="$emit('update:visible', $event)"
    :header="isEdit ? '编辑用户' : '新建用户'"
    :width="720"
    :footer="false"
    @close="handleClose"
  >
    <div class="user-form-container">
      <t-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
        :colon="true"
        @submit="handleSubmit"
      >
        <t-row :gutter="24">
          <!-- 基本信息 -->
          <t-col :span="12">
            <t-form-item label="用户名" name="username">
              <t-input
                v-model="formData.username"
                placeholder="请输入用户名"
                :disabled="isEdit"
                clearable
              />
            </t-form-item>
          </t-col>
          
          <t-col :span="12">
            <t-form-item label="昵称" name="nickname">
              <t-input
                v-model="formData.nickname"
                placeholder="请输入昵称"
                clearable
              />
            </t-form-item>
          </t-col>
          
          <t-col :span="12">
            <t-form-item label="邮箱" name="email">
              <t-input
                v-model="formData.email"
                placeholder="请输入邮箱"
                type="email"
                clearable
              />
            </t-form-item>
          </t-col>
          
          <t-col :span="12">
            <t-form-item label="手机号" name="phone">
              <t-input
                v-model="formData.phone"
                placeholder="请输入手机号"
                clearable
              />
            </t-form-item>
          </t-col>
          
          <!-- 密码设置 (仅新建时显示) -->
          <template v-if="!isEdit">
            <t-col :span="12">
              <t-form-item label="密码" name="password">
                <t-input
                  v-model="formData.password"
                  type="password"
                  placeholder="请输入密码"
                  clearable
                />
              </t-form-item>
            </t-col>
            
            <t-col :span="12">
              <t-form-item label="确认密码" name="confirmPassword">
                <t-input
                  v-model="formData.confirmPassword"
                  type="password"
                  placeholder="请再次输入密码"
                  clearable
                />
              </t-form-item>
            </t-col>
          </template>
          
          <!-- 角色和状态 -->
          <t-col :span="12">
            <t-form-item label="角色" name="roleIds">
              <t-select
                v-model="formData.roleIds"
                placeholder="请选择角色"
                multiple
                clearable
              >
                <t-option
                  v-for="role in roleOptions"
                  :key="role.id"
                  :value="role.id"
                  :label="role.name"
                />
              </t-select>
            </t-form-item>
          </t-col>
          
          <t-col :span="12">
            <t-form-item label="状态" name="status">
              <t-select
                v-model="formData.status"
                placeholder="请选择状态"
              >
                <t-option value="active" label="启用" />
                <t-option value="inactive" label="禁用" />
              </t-select>
            </t-form-item>
          </t-col>
          
          <!-- 部门信息 -->
          <t-col :span="12">
            <t-form-item label="部门" name="departmentId">
              <t-tree-select
                v-model="formData.departmentId"
                :data="departmentOptions"
                placeholder="请选择部门"
                clearable
              />
            </t-form-item>
          </t-col>
          
          <t-col :span="12">
            <t-form-item label="职位" name="position">
              <t-input
                v-model="formData.position"
                placeholder="请输入职位"
                clearable
              />
            </t-form-item>
          </t-col>
          
          <!-- 个人信息 -->
          <t-col :span="12">
            <t-form-item label="性别" name="gender">
              <t-radio-group v-model="formData.gender">
                <t-radio value="male">男</t-radio>
                <t-radio value="female">女</t-radio>
                <t-radio value="other">其他</t-radio>
              </t-radio-group>
            </t-form-item>
          </t-col>
          
          <t-col :span="12">
            <t-form-item label="生日" name="birthday">
              <t-date-picker
                v-model="formData.birthday"
                placeholder="请选择生日"
                clearable
              />
            </t-form-item>
          </t-col>
          
          <!-- 备注 -->
          <t-col :span="24">
            <t-form-item label="备注" name="remark">
              <t-textarea
                v-model="formData.remark"
                placeholder="请输入备注信息"
                :autosize="{ minRows: 3, maxRows: 5 }"
              />
            </t-form-item>
          </t-col>
        </t-row>
        
        <!-- 表单按钮 -->
        <div class="form-footer">
          <t-space>
            <t-button @click="handleClose">取消</t-button>
            <t-button 
              theme="primary" 
              type="submit"
              :loading="loading"
            >
              {{ isEdit ? '保存' : '创建' }}
            </t-button>
          </t-space>
        </div>
      </t-form>
    </div>
  </t-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'

// 定义 props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  userData: {
    type: Object,
    default: () => ({})
  },
  mode: {
    type: String,
    default: 'create' // 'create' | 'edit'
  },
  loading: {
    type: Boolean,
    default: false
  }
})

// 定义 emits
const emit = defineEmits(['update:visible', 'submit', 'close'])

// 表单引用
const formRef = ref(null)

// 计算属性
const isEdit = computed(() => props.mode === 'edit')

// 表单数据
const formData = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  roleIds: [],
  status: 'active',
  departmentId: '',
  position: '',
  gender: '',
  birthday: '',
  remark: ''
})

// 表单验证规则
const formRules = reactive({
  username: [
    { required: true, message: '请输入用户名', type: 'error' },
    { min: 3, max: 20, message: '用户名长度为3-20位', type: 'error' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', type: 'error' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', type: 'error' },
    { min: 2, max: 50, message: '昵称长度为2-50位', type: 'error' }
  ],
  email: [
    { required: true, message: '请输入邮箱', type: 'error' },
    { type: 'email', message: '请输入正确的邮箱格式', type: 'error' }
  ],
  phone: [
    { required: true, message: '请输入手机号', type: 'error' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', type: 'error' }
  ],
  password: [
    { required: true, message: '请输入密码', type: 'error' },
    { min: 6, max: 20, message: '密码长度为6-20位', type: 'error' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', type: 'error' },
    { 
      validator: (val) => val === formData.password, 
      message: '两次输入的密码不一致', 
      type: 'error' 
    }
  ],
  status: [
    { required: true, message: '请选择状态', type: 'error' }
  ]
})

// 角色选项
const roleOptions = ref([
  { id: '1', name: '超级管理员' },
  { id: '2', name: '管理员' },
  { id: '3', name: '普通用户' },
  { id: '4', name: '访客' }
])

// 部门选项
const departmentOptions = ref([
  {
    label: '总经理办公室',
    value: '1',
    children: [
      { label: '人事部', value: '1-1' },
      { label: '财务部', value: '1-2' }
    ]
  },
  {
    label: '技术部',
    value: '2',
    children: [
      { label: '前端开发组', value: '2-1' },
      { label: '后端开发组', value: '2-2' },
      { label: '测试组', value: '2-3' }
    ]
  },
  {
    label: '运营部',
    value: '3',
    children: [
      { label: '市场推广组', value: '3-1' },
      { label: '客户服务组', value: '3-2' }
    ]
  }
])

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    username: '',
    nickname: '',
    email: '',
    phone: '',
    password: '',
    confirmPassword: '',
    roleIds: [],
    status: 'active',
    departmentId: '',
    position: '',
    gender: '',
    birthday: '',
    remark: ''
  })
  
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 填充表单数据
const fillFormData = (userData) => {
  Object.assign(formData, {
    username: userData.username || '',
    nickname: userData.nickname || '',
    email: userData.email || '',
    phone: userData.phone || '',
    roleIds: userData.roleIds || [],
    status: userData.status || 'active',
    departmentId: userData.departmentId || '',
    position: userData.position || '',
    gender: userData.gender || '',
    birthday: userData.birthday || '',
    remark: userData.remark || ''
  })
}

// 处理提交
const handleSubmit = ({ validateResult }) => {
  if (validateResult === true) {
    const submitData = { ...formData }
    
    // 编辑模式下移除密码字段
    if (isEdit.value) {
      delete submitData.password
      delete submitData.confirmPassword
    }
    
    emit('submit', submitData)
  }
}

// 处理关闭
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    if (isEdit.value && props.userData) {
      fillFormData(props.userData)
    } else {
      resetForm()
    }
  }
})

// 监听用户数据变化
watch(() => props.userData, (newVal) => {
  if (props.visible && isEdit.value && newVal) {
    fillFormData(newVal)
  }
}, { deep: true })

// 编辑模式下移除密码验证规则
watch(() => props.mode, (newMode) => {
  if (newMode === 'edit') {
    delete formRules.password
    delete formRules.confirmPassword
  } else {
    formRules.password = [
      { required: true, message: '请输入密码', type: 'error' },
      { min: 6, max: 20, message: '密码长度为6-20位', type: 'error' }
    ]
    formRules.confirmPassword = [
      { required: true, message: '请确认密码', type: 'error' },
      { 
        validator: (val) => val === formData.password, 
        message: '两次输入的密码不一致', 
        type: 'error' 
      }
    ]
  }
})
</script>

<style scoped>
.user-form-container {
  padding: 24px;
}

.form-footer {
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid var(--td-border-level-1-color);
  display: flex;
  justify-content: flex-end;
}

/* 表单样式增强 */
:deep(.t-form-item) {
  margin-bottom: 24px;
}

:deep(.t-form-item__label) {
  font-weight: 500;
  color: var(--td-text-color-primary);
}

:deep(.t-input),
:deep(.t-select),
:deep(.t-tree-select),
:deep(.t-date-picker),
:deep(.t-textarea) {
  border-radius: 6px;
  transition: all 0.2s;
}

:deep(.t-input:hover),
:deep(.t-select:hover),
:deep(.t-tree-select:hover),
:deep(.t-date-picker:hover) {
  border-color: var(--td-brand-color);
}

:deep(.t-radio-group) {
  display: flex;
  gap: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-form-container {
    padding: 16px;
  }
  
  :deep(.t-col) {
    width: 100% !important;
  }
}
</style> 